package com.wstuo.common.jaas.action;
import java.io.IOException;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
import javax.security.sasl.AuthenticationException;

/**
 * Kerberos 认证
 * @author Administrator
 *
 */
public class KerberosAuthenticator {
	
	/**
	 * Kerberos 验证
	 * @param username 登录名
	 * @param password 密码
	 * @throws AuthenticationException
	 * @throws LoginException
	 */
	public void authenticateForPortal(String username, String password)
									throws AuthenticationException, LoginException {
		LoginContext lc = null;
		lc = new LoginContext("ldap", new KerberosCallbackHandler(username, password));
		lc.login();
		lc.getSubject();
	}


	class KerberosCallbackHandler implements CallbackHandler {
		private String username;
		private String password;
	
		public KerberosCallbackHandler(String username, String password) {
			super();
			this.username = username;
			this.password = password;
		}
	
		public void handle(Callback[] callbacks) throws IOException,
														UnsupportedCallbackException {
			for (int i=0; i < callbacks.length; i++) {
				if (callbacks[i] instanceof NameCallback) {
					NameCallback ncb = (NameCallback) callbacks[i];
					ncb.setName(username);
				} else if (callbacks[i] instanceof PasswordCallback) {
					PasswordCallback pcb = (PasswordCallback) callbacks[i];
					pcb.setPassword(this.password.toCharArray());
				}
			}
		}
	}
}
